package com.ask.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ask.constants.RedisConstant;
import com.ask.dto.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.ask.constants.RedisConstant.*;

@Component
public class CacheClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 普通缓存
     *
     * @param key
     * @param data
     * @param timeOut
     * @param unit
     */
    public void save2Redis(String key, Object data, Long timeOut, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(data), timeOut, unit);
    }


    /**
     * 普通换缓存（设置逻辑过期时间）
     *
     * @param key
     * @param data
     * @param time
     * @param unit
     */
    public void save2RedisWithLogicalExpire(String key, Object data, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(data);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(data));
    }

    /**
     * 缓存（缓存穿透解决）
     *
     * @param keyPreFix
     * @param type
     * @param id
     * @param dbFallBack
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R, ID> R queryWithPassThrough(
            String keyPreFix, Class<R> type, ID id, Function<ID, R> dbFallBack,
            Long time, TimeUnit unit) {
        // 查询redis缓存
        String key = keyPreFix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 缓存命中直接返回
        if (StrUtil.isNotBlank(json))
            return JSONUtil.toBean(json, type);
        // 缓存为空值
        if (json != null)
            return null;

        // 缓存未命中,查询数据库
        R r = dbFallBack.apply(id);

        // 数据库中不存在，缓存空值
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key, "", EMPTY_CACHE_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 数据库存在，存储至redis
        this.save2Redis(key, r, time, unit);

        // 返回查询到的店铺信息
        return r;
    }

    // 缓存池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public <R, ID> R queryWithLogicalExpire(String keyPreFix, Class<R> type, ID id, Function<ID, R> dbFallBack, Long time, TimeUnit unit) {
        // 查询redis
        String key = keyPreFix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 缓存未命中直接返回null
        if (StrUtil.isBlank(json))
            return null;

        // 缓存命中
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R rCache = JSONUtil.toBean((JSONObject) redisData.getData(), type);

        // 缓存未过期，直接返回
        if (redisData.getExpireTime().isAfter(LocalDateTime.now()))
            return rCache;

        // 缓存过期，获取锁
        String lockKey = CACHE_LOCK_KEY + id;
        boolean getLock = tryLock(lockKey);
        // 拿到锁，开启独立线程进行缓存重建,设置逻辑过期时间
        if (getLock) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R rDb = dbFallBack.apply(id);
                    save2RedisWithLogicalExpire(key, rDb, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        // 缓存未过期，直接返回
        return rCache;
    }

    /**
     * redis互斥锁加锁
     *
     * @param id
     * @return
     */
    private <ID> boolean tryLock(ID id) {
        String lockKey = CACHE_LOCK_KEY + id;
        Boolean res = stringRedisTemplate.
                opsForValue().setIfAbsent(lockKey, "1", CACHE_LOCK_TTL, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(res);
    }

    /**
     * redis互斥锁解锁
     *
     * @param id
     */
    private <ID> void unLock(ID id) {
        String lockKey = CACHE_LOCK_KEY + id;
        stringRedisTemplate.delete(lockKey);
    }
}
